﻿using UnityEngine;
using System.Collections;
using UnityNetwork;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;

#if ENABLE_WINMD_SUPPORT
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.ApplicationModel.Core;
#endif

public class ChatManager : NetworkManager
{
    public Action ActionConnectedTCPSuccess = MainControl.CurrentMainControl.InitCamera;
    public TCPPeer client;

    public string ip = "";
    public int port = 0;
    public static bool ConnectStateFlag = false;
    public static bool snapImgFlag = false;

    public void Connecting()
    {
        client = new TCPPeer(this);
        client.Connect(ip, port);       
    }

    public void Send(NetPacket packet)
    {
        if (client.socket.Connected )
        {
            client.Send(client.socket, packet);
        }
    }

    public override void OnLost(NetPacket packet)
    {
        ConnectStateFlag = false;
#if ENABLE_WINMD_SUPPORT
        TextToSpeech.Instance.StartSpeaking("服务器连接丢失即将关闭应用");
#elif UNITY_EDITOR
        Debug.Log("服务器连接丢失");
#endif

        client.socket.Close();
        client.socket.Dispose();

        Thread.Sleep(5000);

#if ENABLE_WINMD_SUPPORT
            CoreApplication.Exit();
#endif
    }

    public override void OnConnected(NetPacket packet)
    {
#if ENABLE_WINMD_SUPPORT
        TextToSpeech.Instance.StartSpeaking("网络连接成功");
#elif UNITY_EDITOR
        Debug.Log("网络连接成功");
#endif
        ConnectStateFlag = true;
        ActionConnectedTCPSuccess();
    }

    public override void OnConnectFailed(NetPacket packet)
    {
        ConnectStateFlag = false;
#if ENABLE_WINMD_SUPPORT
        TextToSpeech.Instance.StartSpeaking("服务器连接失败即将关闭应用");
#elif UNITY_EDITOR
        Debug.Log("服务器连接失败");
#endif
     
    Thread.Sleep(5000);
    client.socket.Close();
    client.socket.Dispose();

#if ENABLE_WINMD_SUPPORT
       CoreApplication.Exit();
#endif
    }

    #region -----------------接收和发送字符串、包含接收命令--------------------
    public void OnReciveString(NetPacket packet)
    {
        string meg = "";
        packet.ReadString(out meg);
        if (meg.Contains("SnapImage")) // 
        {
            snapImgFlag = true;
        }
        if (meg.Contains("CloseApp"))// CloseApp
        {
            client.socket.Shutdown(System.Net.Sockets.SocketShutdown.Both);
            client.socket.Disconnect(false);
            client.socket.Close();
            client.socket.Dispose();

            TextToSpeech.Instance.StartSpeaking("即将关闭应用");
            Thread.Sleep(2000);

#if ENABLE_WINMD_SUPPORT
            CoreApplication.Exit();
#endif
        }
    }
    //------
    public void SendCommand(string Meg)
    {
        NetPacket packet = new NetPacket();

        packet.BeginWrite((int)ConfigSet.megcls.ClientSendCommand);
        packet.WriteString(Meg);
        packet.EncodeHeader();
        AddPacket_to_sendPackets(packet);

    }
    public void OnSendCommand(NetPacket packet)
    {
        string meg = "";
        packet.ReadString(out meg);

        packet.BeginWrite((int)ConfigSet.megcls.ClientSendCommand);
        packet.WriteString(meg);
        packet.EncodeHeader();

        this.Send(packet);
    }
    #endregion

    #region-------- 发送文件 （相机原图）---------------
    public void SendCameraPic(byte[] image)
    {
        NetPacket File_packet = new NetPacket();
        File_packet.BeginWrite((int)ConfigSet.megcls.ClientSnapPic);
        File_packet.WriteStream(image);
        File_packet.EncodeHeader();
        AddPacket_to_sendPackets(File_packet);
    }

    public void OnSendCameraPic(NetPacket packet)
    {
        byte[] img = packet.ReadStream();

        packet.BeginWrite((int)ConfigSet.megcls.ClientSnapPic);
        packet.WriteStream(img);
        packet.EncodeHeader();

        this.Send(packet);

        GC.Collect();
    }

    #endregion
   
    #region ----- 接收标定好的内参并保存在 document/intric 文件夹中 ---------
    public async void OnReciveIntric(NetPacket packet)
    {
        float[] Intric = new float[14];
        for (int i = 0; i < 14; i++)
        {
            packet.ReadFloat(out Intric[i]);
        }

        byte[] bytes = new byte[14 * 4];
        for (int i = 0; i < 14; i++)
        {
            BitConverter.GetBytes(Intric[i]).CopyTo(bytes, i * 4);
        }

        await UWPFileOpration.SaveFileToLibrary("RGBCameraintric", bytes, 2, "intric");
        SendCommand("SaveIntrincSuccess");
        TextToSpeech.Instance.StartSpeaking("保存内参文件完毕");

    }

    #endregion----------------------

    #region ---- 发送API 得到的内参 ----
    public void SendIntrics(float fx, float fy, float cx, float cy)
    {
        NetPacket File_packet = new NetPacket();
        File_packet.BeginWrite((int)ConfigSet.megcls.ClientSendIntric);
        File_packet.WriteFloat(fx);
        File_packet.WriteFloat(fy);
        File_packet.WriteFloat(cx);
        File_packet.WriteFloat(cy);
        File_packet.EncodeHeader();
        AddPacket_to_sendPackets(File_packet);
    }

    public void OnSendIntrics(NetPacket packet)
    {
        float fx, fy, cx, cy;

        packet.ReadFloat(out fx);
        packet.ReadFloat(out fy);
        packet.ReadFloat(out cx);
        packet.ReadFloat(out cy);

        packet.BeginWrite((int)ConfigSet.megcls.ClientSendIntric);
        packet.WriteFloat(fx);
        packet.WriteFloat(fy);
        packet.WriteFloat(cx);
        packet.WriteFloat(cy);
        packet.EncodeHeader();

        this.Send(packet);
    }
    #endregion

}

